<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->
    <title-name :title="'日常资料管理_'+form.taskName"></title-name>
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-spin :spinning="loading">
        <a-card :bordered="false" v-if="typess != 'read'">
          <title-name title="节点信息"></title-name>
          <custom-form :form="form" :formList="formListNode" :editModel="editModel == 0 ? '' : ''" @getProjectInfo="getProjectInfo"> </custom-form>
        </a-card>
        <a-card :bordered="false" v-if="typess != 'read'">
          <title-name title="审批"></title-name>
          <custom-form :form="form" :formList="auditXMZG" :editModel="editModel == 0 ? '' : ''" @getProjectInfo="getProjectInfo"> </custom-form>
          <Consultation
            :proc-inst-id="procInstId"
            :is-show-btn="$route.query.isMonitoring ? ($route.query.monitoringType==='process' ? true: false): true"
            :task-name="taskName"
            :sub-approver-list.sync="subApproverList"
          >
            <template slot="approverButton">
              <a-button type="primary" :loading="loading.PASS" @click="handleSave('PASS')">审批通过</a-button>
              <a-button type="primary" class="ml12" :loading="loading.REJECT" @click="handleSave('REJECT')">审批不通过</a-button>
            </template>
          </Consultation>
        </a-card>
        <a-card>
          <template>
            <title-name title="审批流程信息" />
            <div class="btns-wrapp mb20">
              <a-button type="primary" @click="visibleState.auditProcess = true"> 审批流程图 </a-button>
            </div>
            <a-spin tip="流程信息加载中..." :spinning="flowRequesting" />
            <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
              <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
              <template slot="opinions" slot-scope="text">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span> {{ text }}</span>
                  </template>
                  <span> {{ text }}</span>
                </a-tooltip>
              </template>
            </a-table>
          </template>
        </a-card>
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="日常资料管理"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @getProjectInfo="getProjectInfo"></custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" style="top: 15px">
          <!-- <a-button v-if="typess == 'read'" type="primary" @click="handleClose">关闭</a-button> -->
          <a-button  @click="handleActiveClose">关闭</a-button>
        </div>
        <ApprovalDetails
          :title="'审批流程信息'"
          :business-id="id"
          :visible="visibleState.auditProcess"
          @cancel="visibleState.auditProcess = false"
          @confirm="visibleState.auditProcess = false"
        />
      </a-spin>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
// import {
//     getTechnicalYearlyPlanById,
//     addTechnicalYearlyPlan,
//     updateTechnicalYearlyPlan
// } from '@/api/technical/technicalReview'
import { addList, editList, getDetails } from '@/api/technical/dailyDataManag'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import ASelectOrgPeople from "@/components/Select/ASelectOrgPeople"
import ApprovalDetails from '@/components/approvalDetails'
import { columnApprove } from './model.js'

import { messageRead } from '@/api/messageSend'
import { getOrgEmployeesListBy } from '@/api/commons'
import { getProcessNodeList, completeTask } from '@/api/process'
import moment from 'moment'
import Vue from 'vue'
import Consultation from '@/views/matters/approval/components/consultation'
import { createAgency } from "@/api/technology"
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal,
    SelectPersonByProject,
    ApprovalDetails,
    Consultation
  },
  data() {
    return {
      columnApprove,
      visibleState: {
        auditProcess: false
      },
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        technicalReviewYearlyPlans: [],
        projectDeptId: '',
        sendPersonName: '',
        receiveUnitName: '',
        sendUnitName: '',
        receivePersonName: '',
        opinions: '',
        cc: [],
        currentTime: '',
        time: ''
      }, // 表单
      id: '',
      yearsOpen: false,
      projectName: '',
      loadingBtn: {
        PASS: false,
        REJECT: false,
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      detailId: '',
      rules: {
        messageType: [{ required: true, message: '请选择' }],
        messageName: [{ required: true, message: '请输入' }],
        messageNumber: [{ required: true, message: '请输入' }],
        dataType: [{ required: true, message: '请选择' }],
        messageAbstract: [{ required: true, message: '请输入' }],
        sendUnitName: [{ required: true, message: '请输入' }],
        sendPersonName: [{ required: true, message: '请输入' }],
        receiveUnitName: [{ required: true, message: '请输入' }],
        receivePersonName: [{ required: true, message: '请输入' }],
        receiveTime: [{ required: true, message: '请选择' }],
        remarks: [{ required: true, message: '请输入' }],
        // opinions: [{ required: true, message: '请输入' }],
        cc: [{ required: true, message: '请选择' ,type: "array"}]
      },
      typess: '',
      init: false, // 初始化控件
      titles: ['日常资料管理查看', '日常资料管理编辑', '日常资料管理新增'],
      //审批相关
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      // 下级审批人
      subApproverList: []
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    'form.messageType'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          if (this.form.messageType == 0) {
            this.form.sendUnitName = this.form.projectName
            this.form.receiveUnitName = ''
          } else {
            this.form.receiveUnitName = this.form.projectName
            this.form.sendUnitName = ''
          }
          this.form.receivePersonName = ''
          this.form.sendPersonName = ''
        })
      }
    }
  },
  mounted() {
    this.formattingData() //格式化审批流数据
    this.readMessage()
  },
  computed: {
    formList() {
      return [
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: e => {
        //     console.log(e)
        //     this.$set(this.form, 'projectDeptId', e.projectDeptId)

        //     this.form.sendUnitName = e?.name
        //     this.form.projectName = e?.name
        //   }
        // },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          span: 16,
          disabled: true,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          viewName: "viewName"
        },
        {
          keyName: 'messageType',
          type: 'a-select',
          label: '收发文类型',
          disabled: this.editModel == 0,
          data: [
            {
              label: '发文',
              value: '0'
            },
            {
              label: '收文',
              value: '1'
            }
          ],
          change: e => {
            if (this.form.messageType == 0) {
              this.form.sendUnitName = this.form.projectName
            } else {
              this.form.sendUnitName = ''
            }
          }
        },
        {
          keyName: 'messageName',
          type: 'BaseInput',
          label: '文件名称',
          disabled: this.editModel == 0
        },
        {
          keyName: 'messageNumber',
          type: 'BaseInput',
          label: '文件编号',
          disabled: this.editModel == 0
        },
        {
          keyName: 'dataType',
          type: 'a-select',
          label: '资料类型',
          disabled: this.editModel == 0,
          data: [
            {
              label: '普通',
              value: '0'
            },
            {
              label: '重大',
              value: '1'
            }
          ]
        },
        {
          keyName: 'messageAbstract',
          type: 'BaseTextarea',
          label: '内容摘要',
          disabled: this.editModel == 0,
          span: 24
        },
        {
          keyName: 'sendUnitName',
          type: 'BaseInput',
          hidden: this.form.messageType != 0,
          label: '发文单位',
          disabled: true
        },
        {
          keyName: 'sendUnitName',
          type: 'BaseInput',
          hidden: this.form.messageType != 1,
          label: '发文单位',
          disabled: this.editModel == 0
        },
        {
          keyName: 'sendPersonName',
          type: 'BaseInput',
          label: '发放人',
          hidden: this.form.messageType != 1,
          disabled: this.editModel == 0
        },
        {
          keyName: 'sendPersonName',
          type: SelectPersonByProject,
          hidden: this.form.messageType != 0,
          disabled: this.editModel == 0,
          label: '发放人',
          wrap: true,
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId
          }
        },
        {
          keyName: 'receiveUnitName',
          type: 'BaseInput',
          hidden: this.form.messageType != 1,
          label: '签收单位',
          disabled: true
        },
        {
          keyName: 'receiveUnitName',
          type: 'BaseInput',
          hidden: this.form.messageType != 0,
          label: '签收单位',
          disabled: this.editModel == 0
        },

        {
          keyName: 'receivePersonName',
          type: 'BaseInput',
          label: '签收人',
          hidden: this.form.messageType != 0,
          disabled: this.editModel == 0
        },
        {
          keyName: 'receivePersonName',
          type: SelectPersonByProject,
          hidden: this.form.messageType != 1,
          disabled: this.editModel == 0,
          label: '签收人',
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId
          }
        },
        {
          keyName: 'receiveTime',
          type: 'a-date-picker',

          disabled: this.editModel == 0,
          label: '签收时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'remarks',
          type: 'BaseTextarea',
          label: '备注',
          disabled: this.editModel == 0,
          span: 24
        },
        {
          keyName: 'fileInfoList',
          type: 'uploadFile',
          label: '附件',
          disabled: this.editModel == 0,
          span: 24,
          businessCode: 'BIM06'
        }
      ]
    },
    formListNode() {
     return [
       {
         keyName: 'taskName',
         type: 'BaseInput',
         label: '当前节点名称',
         disabled: true,

         span: 8
       },
       {
         keyName: 'currentUser',
         type: 'BaseInput',
         label: '审批人',
         disabled: true,

         span: 8
       },
       {
         keyName: 'time',
         type: 'BaseInput',
         label: '审批时间',
         disabled: true,

         span: 8
       }
     ]
    },
    auditXMZG() {
      console.log(this.form,this.taskDefKey, 'this.taskDefKey' )
      return [
        {
          keyName: 'cc',
          type: ASelectOrgPeople,
          hidden: !(this.form.dataType == 0 && this.taskDefKey == 'PD_ZG_AUDIT' && this.form.messageType == 1),
          // disabled: this.editModel == 0,
          label: '下发人',
          required: true,
          attrs: {
            showSearch: true,
            orgId: '53085e2c9f1f4685801ef31994f57c49',
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'cc',
          type: ASelectOrgPeople,
          hidden: !(this.form.dataType == 1 && this.taskDefKey == 'PD_XMJL_AUDIT'&&this.form.messageType == 1),
          // disabled: this.editModel == 0,
          label: '下发人',
          required: true,
          attrs: {
            showSearch: true,
            orgId: '53085e2c9f1f4685801ef31994f57c49',
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'cc',
          type: ASelectOrgPeople,
          hidden: !(this.form.dataType == 0 && this.taskDefKey == 'PD_ZG_AUDIT'&&this.form.messageType == 0),
          label: '抄送人',
          required: true,
          attrs: {
            showSearch: true,
            orgId: '53085e2c9f1f4685801ef31994f57c49',
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'cc',
          type: ASelectOrgPeople,
          hidden: !(this.form.dataType == 1 && this.taskDefKey == 'PD_XMJL_AUDIT'&&this.form.messageType == 0),
          label: '抄送人',
          required: true,
          attrs: {
            showSearch: true,
            orgId: '53085e2c9f1f4685801ef31994f57c49',
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'opinions',
          type: 'BaseTextarea',
          label: '审批意见',
          required: true,
          span: 24
        },
      ]
    }
  },
  methods: {
    readMessage() {
      if (!this.detailId) return
      const params = {
        ids: [this.detailId]
      }
      messageRead(params).then(res => {
        if (res && res.data && res.data.code == '200') {
          this.$message.success('查看成功！')
          let count = Number(this.$store.getters['messageInfo/GET_TOREADCOUNT'] - 1)
          this.$store.commit('messageInfo/SET_TOREADCOUNT', count > 0 ? count : 0)
        } else {
          this.$message.error(res.data.message ? res.data.message : '查看失败！')
        }
      })
    },
    formattingData() {
      try {
        setTimeout(() => {
          const requireDom = document.querySelectorAll('.ant-form-item-required')
          requireDom.forEach(item => {
            item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
          })
        }, 0)
      } catch {}
      this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
      this.id = this.$route.query.id
      const {
        type,
        code,
        level,
        btype,
        businessId,
        procInstId,
        name,
        processName,
        detailUrl,
        taskId,
        taskDefKey,
        durationInMillis
      } = this.$route.query
      if (type) {
        this.assignType = type
        this.assignCode = code
        this.assignLevel = level
        this.businessType = btype
      }
      this.id = businessId
      this.detailId = this.$route.query.detailId
      this.typess = this.$route.query.typess
      // this.taskDefKey = 'GS_CWZJBJL_AUDIT'
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      console.log(this.$route.query)
      this.procInstId = procInstId
      this.form.currentUser = Vue.getAcloudProvider().getUserInfo().name
      this.form.taskName = decodeURIComponent(name)
      this.taskName =   this.form.taskName
      this.form.durationInMillis = durationInMillis
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      this.taskId = taskId
      this.taskDefKey = taskDefKey

      this.form.time = moment(new Date()).format('YYYY-MM-DD HH:mm')
      this.currentTime = this.form.currentTime
      this.$route.meta.title = '日常资料管理'
      this.getDetails()
      this.getProcessNodes()
    },
    //流程节点信息
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then(res => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map(d => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
              this.flowRequesting = false
              res.data.forEach(r => {
                employees.data.some(e => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })

              this.approveInfos = res.data
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    },
    getDetails() {
      this.loading = true
      getDetails({ id: this.id })
        .then(res => {
          this.loading = false
          this.form = { ...this.form, ...res.data }
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 处理增、删、改操作
    handleSave(status) {
      if (this.loadingBtn[status]) return

      if (status == 'PASS') {
        if (this.validateForm()) {
          this.handelApproval(status)
        }
      } else {
        this.handelUnApproval(status)
      }
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate(e => {
        if (e) {
          flag = true
        }
      })

      return flag
    },
    handelApproval(staus) {
      // 审批通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(false, _this.createApproverList(_this.subApproverList))
              .then(() => {

                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch((err) => {
            console.log(err)
            this.$error({ content: '审批提交失败，请稍后重试' })
          })
        },
        onCancel() {}
      })
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    handelUnApproval(staus) {
      // 审批不通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    handleClose() {
      this.$multiTab.close()
    },
    /**
     * @description: 组装下级审批人数据
     * @param {array} subApproverList 下级审批人表格数据
     * @return {object} 下级审批人数据
     */
    createApproverList(subApproverList) {
      const subordinateApproverList = {}
      subApproverList.forEach((item) => {
        if (item?.approver && item.approver.length > 0) {
          subordinateApproverList[item.taskInfo.id] = {
            assgins: item.approver?.map((el) => el.key).join(','),
            assignTypeEnum: 2
          }
        }
      })
      return subordinateApproverList
    },
    async submit(reject) {

      delete this.form.auditStatus

      const data = {
        formData: {
          opinions: this.form.opinions || '同意',
          // cc: this.form.cc?.join(','),
          content:
            (this.form.messageType == 0 ? '发文' : '收文') +
            (this.form.dataType == 0 ? '(普通)' : '(重大)') +
            this.form.messageName,
          title: '日常资料管理',
          // messageTx: this.form.messageType == 0 ? '发文' : '收文',
          // messageName: this.form.messageName, //文件名称
          // dataType: this.form.dataType == 0 ? '普通' : '重大',
          reject
        },
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: Vue.getAcloudProvider().getUserInfo().id
      }
      if (reject) {
        data['variables'] = { reject: true }
      }
      // const params = {
      //   managementId: '1630452308997443584',
      //   receivePersonId: '753623f8af27436a94fe718b468adec3'
      // }
      //  createAgency(params)
      // return
      return completeTask(data)
        .then( async res => {
          if (res.status === 200) {

            if(this.form.cc?.length) {
              const params = {
                managementId: this.id,
                receivePersonId: this.form.cc.join(",")
              }
              if(!reject) {
                await createAgency(params)
              }
            }

            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch(err => {
          return err
        })
    },
    /**
     * @description: 所属单位获取项目信息设置组织id
     * @param {object} info 项目信息
     * @return {void}
     */    
    getProjectInfo(info){
      this.form.projectDeptId = info?.projectDeptOrgId
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
.item {
  margin-left: 60px;
  margin-bottom: 0;
}
.item .ant-form-item {
  margin-top: -28px;
}
</style>
